<template>
  <div id="Roles">
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图 -->
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRoles">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="rolelist" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']" v-for="(item1, i1) in scope.row.children" :key="item1.id">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag @close="removeRightById(scope.row,item1.id)" :closable="true">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <!-- 通过for 循环嵌套渲染二级权限 -->
                <el-row :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']" v-for="(item2, i2) in item1.children" :key="item2.id">
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag @close="removeRightById(scope.row,item2.id)" :closable="true" type="success">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <!-- 渲染三级权限 -->
                    <el-tag @close="removeRightById(scope.row,item3.id)" :closable="true" type="warning" v-for="(item3, i3) in item2.children" :key="item3.id">{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="290px">
          <template slot-scope="scope">
            <el-button @click="showEditDialog(scope.row.id)" size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
            <el-button @click="removeRolesById(scope.row.id)" size="mini" type="danger" icon="el-icon-delete">删除</el-button>
            <el-button @click="showSetRightDialog(scope.row)" size="mini" type="warning" icon="el-icon-setting">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加修改角色弹窗区域 -->
    <el-dialog
      :title="isAddOrUpdate === 'add' ? '添加角色' : '修改角色' "
      :visible.sync="addDialogVisible"
      width="30%" @close="addDialogClosed" 
      >
      <!-- 内容主体区域 -->
      <el-form :model="rolesForm" :rules="rolesFormRules" ref="rolesFormRef" label-width="90px" >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="rolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="rolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateRoles">确 定</el-button>
      </span>
  </el-dialog>
  <!-- 分配权限窗口 -->
  <el-dialog
    title="分配权限"
    :visible.sync="setRightDialogVisible"
    width="50%" @close="setRightDialogClosed"
    >
    <!-- 所有权限树形结构 -->
    <el-tree :data="rightslist" :props="treeProps" 
     show-checkbox node-key="id" 
     :default-expand-all="true"
     :default-checked-keys="defKeys" 
     ref="treeRef">
    </el-tree>
    <span slot="footer" class="dialog-footer">
      <el-button @click="setRightDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="allotRights">确 定</el-button>
    </span>
  </el-dialog>
  </div>
</template>

<script>
import { getHttpRolesList, postHttpAddRoles, getHttpGetRolesById, putHttpUpdateRolesById, deleteHttpDeleteRolesById, deleteHttpDeleteRightById, getHttpRightsList, postHttpUpdateRolesRights  } from 'network/roles'
import { rolenameVf, roledescVf } from 'common/js/validator'
export default {
  name: "Roles",
  data() {
    return {
      //所有角色列表
      rolelist: [],
      //添加修改角色表单
      rolesForm: {
        roleId: '',
        roleName: '',
        roleDesc: ''
      },
      //添加编辑角色验证规则
      rolesFormRules: {
        roleName:rolenameVf,
        roleDesc:roledescVf
      },
      isAddOrUpdate: '',
      //新增编辑权限弹窗是否显示
      addDialogVisible: false,
      //分配权限弹窗是否显示
      setRightDialogVisible: false,
      //所有权限列表
      rightslist: [],
      //树形控件的属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      //默认选中的节点ID值数组
      defKeys: [],
      //保存分配权限时候的角色ID
      roleId: ''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    //请求角色列表
    getRolesList() {
      getHttpRolesList().then(res => {
        if( res.meta.status !== 200) {
          this.$message.error(res.meta.msg)
          return
        }
        else {
          this.rolelist = res.data
        }
      }).catch(err => {
        this.$message.error(err)
      })
    },
    //根据id删除对于的权限
    removeRightById(role,rightId) {
      //弹框提示用户是否要删除
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //开始网络请求删除权限
        deleteHttpDeleteRightById(role.id, rightId).then(res => {
          if( res.meta.status !== 200) {
            this.$message.error(res.meta.msg)
            return
          }
          else {
            //this.getRolesList()
            role.children = res.data
          }
        }).catch(err => {
          this.$message.error(err)
        })   
      }).catch(() => {
        this.$message({type: 'info', message: '已取消删除' })          
      })
    },
    //弹窗关闭事件
    addDialogClosed() {
      //重置表单
      this.$refs.rolesFormRef.resetFields()
      this.isAddOrUpdate = ''
    },
    //添加或者修改角色提交事件
    addOrUpdateRoles() {
      //表单验证
      this.$refs.rolesFormRef.validate(valid => {
        if(!valid) {
          return
        }
        else {
          //如果是添加
          if(this.isAddOrUpdate === 'add') {
            postHttpAddRoles(this.rolesForm).then(res => {
              if( res.meta.status !== 201) {
                this.$message.error(res.meta.msg)
                return
              }
              else {
                this.$message.success(res.meta.msg)
                this.addDialogVisible = false
                this.getRolesList()
                this.isAddOrUpdate = ''
                this.rolesForm.roleId = ''
                this.rolesForm.roleName = ''
                this.rolesForm.roleDesc = ''
              }
            }).catch(err => {
              this.$message.error(err)
            })
          }
        }
        //如果是修改
        if(this.isAddOrUpdate === 'update') {
          const rolesdata = {
            id: this.rolesForm.roleId,
            roleName: this.rolesForm.roleName,
            roleDesc: this.rolesForm.roleDesc
          }
          putHttpUpdateRolesById(rolesdata).then(res => {
            if( res.meta.status !== 200) {
              this.$message.error(res.meta.msg)
              return
            }
            else {
              this.$message.success(res.meta.msg)
              this.addDialogVisible = false
              this.getRolesList()
              this.isAddOrUpdate = ''
              this.rolesForm.roleId = ''
              this.rolesForm.roleName = ''
              this.rolesForm.roleDesc = ''
            }
          }).catch(err => {
            this.$message.error(err)
          })
        }
      })
    },
    //点击添加角色事件
    addRoles() {
      this.addDialogVisible = true
      this.isAddOrUpdate = 'add'
    },
    //编辑角色事件
    showEditDialog(id) {
      //查询角色信息
      getHttpGetRolesById(id).then(res => {
        if( res.meta.status !== 200) {
          this.$message.error(res.meta.msg)
          return
        }
        else {
          //查询到数据以后
          this.rolesForm.roleId = res.data.roleId
          this.rolesForm.roleName = res.data.roleName
          this.rolesForm.roleDesc = res.data.roleDesc
          //打开窗口
          this.addDialogVisible = true
          this.isAddOrUpdate = 'update'
        }
      }).catch(err => {
        this.$message.error(err)
      })     
    },
    //删除角色事件
    removeRolesById(id) {
      //弹窗询问用户是否删除数据
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteHttpDeleteRolesById(id).then(res => {
            if( res.meta.status !== 200) {
              this.$message.error(res.meta.msg)
              return
            }
            else {
              this.$message({type: 'success', message: '删除成功!' })
              this.getRolesList()
            }
          }).catch(err => {
            this.$message.error(err)
          })
          
        }).catch(() => {
          this.$message({ type: 'info',message: '已取消删除' })          
        })
    },
    //分配权限按钮事件
    showSetRightDialog(role) {
      //网络请求权限数据
      getHttpRightsList('tree').then(res => {
        if( res.meta.status !== 200) {
          this.$message.error(res.meta.msg)
          return
        }
        else {         
          this.rightslist = res.data
          //递归获取当前角色3级节点的id
          this.getLeafKeys(role,this.defKeys)
          //把当前角色的ID保存到data中
          this.roleId = role.id
          this.setRightDialogVisible = true
        }
      }).catch(err => {
        this.$message.error(err)
      })
      
    },
    //通过递归的形式，获取角色下所有的三级权限的id，并保存到defKeys数组中
    getLeafKeys(node,arr) {
      //当当前节点是三级节点
      //当前节点不包含children属性，则是3级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    //关闭分配权限弹窗事件
    setRightDialogClosed() {
      this.defKeys = []
    },
    //分配权限确定按钮事件
    allotRights() {
      const keys = [...this.$refs.treeRef.getCheckedKeys(),...this.$refs.treeRef.getHalfCheckedKeys()]
      //被选中的节点的 key 所组成的数组
      this.$refs.treeRef.getCheckedKeys()
      //返回目前半选中的节点的 key 所组成的数组
      this.$refs.treeRef.getHalfCheckedKeys()
      const idStr = keys.join(',')
      //请求网络
      postHttpUpdateRolesRights(this.roleId,idStr).then(res => {
        if( res.meta.status !== 200) {
          this.$message.error(res.meta.msg)
          return
        }
        else {
          this.$message.success(res.meta.msg)
          this.getRolesList()
          this.setRightDialogVisible = false
        }
      }).catch(err => {
        this.$message.error(err)
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
